﻿//https://leetcode.cn/problems/course-schedule/?envType=study-plan-v2&envId=top-100-liked

class Solution {
public:
    bool canFinish(int numCourses, vector<vector<int>>& prerequisites)
    {
        //创建一个邻接表
        unordered_map<int, vector<int>> edges(numCourses);
        vector<int> in(numCourses);

        //构建邻接表矩阵
        for (auto& e : prerequisites)
        {
            int a = e[0], b = e[1];
            edges[b].push_back(a);
            in[a]++;
        }

        //拓扑排序
        //入度为0的进队列
        queue<int> q;
        for (int i = 0; i < in.size(); i++)
        {
            if (in[i] == 0)
                q.push(i);
        }

        while (q.size())
        {
            int a = q.front();
            q.pop();

            for (auto& b : edges[a])
            {
                if (--in[b] == 0)
                {
                    q.push(b);
                }
            }
        }

        //判断是否带环
        for (auto& e : in)
        {
            if (e)
                return false;
        }
        return true;
    }
};